<?php

// Copyright 2019 Hackware SpA <human@hackware.cl>
// Part of "Hackware Web Services Core", released under the MIT License terms.

namespace Hawese\Core\Providers;

use Illuminate\Support\ServiceProvider;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\{
    NativeFileSessionHandler
};
use Symfony\Component\HttpFoundation\Session\Storage\{
    NativeSessionStorage, MockArraySessionStorage
};

class SessionServiceProvider extends ServiceProvider
{
    public function register()
    {
        // Based the following recommendations, assuming use of PHP7 defaults
        // https://www.owasp.org/index.php/Session_Management_Cheat_Sheet

        $this->app->singleton('session', function ($app) {
            if (env('APP_ENV') != 'testing') {
                // @codeCoverageIgnoreStart
                $sessionStorage = new NativeSessionStorage(
                    [
                        // http://php.net/session.configuration, omit session.
                        'name' => 'session',
                        'autostart' => 0,
                        'cookie_lifetime' => 0, // until browser is closed
                        'cookie_path' => '/',
                        'cookie_domain' => null, // origin
                        'cookie_secure' => (
                            $app->environment() == 'production' ? true : false
                        ),
                        'cookie_httponly' => 'true', // do not read through JS
                        'cookie_samesite' => null, // don't care about referer
                    ],
                    new NativeFileSessionHandler(storage_path('sessions'))
                );
                // @codeCoverageIgnoreEnd
            } else {
                $sessionStorage = new MockArraySessionStorage();
            }

            return new Session($sessionStorage);
        });
    }

    public function boot()
    {
        $this->app['session']->start();
    }
}
